package com.jxb.dp;

/**
 * f(n) = f(n-1) + f(n-2)
 */
public class FibonacciNumber_509 {

    public static void main(String[] args) {

    }

    //通过动态规划来实现
    //1：确定状态转移公式：dp[i] = dp[i-1] + dp[i-2]
    //2：初始化dp数组
    //3：根据条件开始遍历，并实现状态转移公式
    public int fib(int n) {
        if (n<=1) {
            return n;
        }
        int[] dp = new int[n+1];
        dp[0] = 0;
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            dp[i] = dp[i-1] + dp[i-2];
        }
        return dp[n];
    }

    //递归
    public int fib1(int n) {
        if (n == 0) {
            return 0;
        }else if (n == 1) {
            return 1;
        }else {
            return fib1(n-1) - fib1(n-2);
        }
    }

    //循环迭代
    public int fib2(int n) {
        if (n <= 1) {
            return n;
        }
        int result = 0;
        int pre = 1;
        int prePre = 0;
        for (int i = 2; i<=n; i++) {
            result = pre + prePre;
            prePre = pre;
            pre = result;
        }
        return result;
    }




}
